import * as fs from "node:fs"
import * as path from "node:path"
import { DBFile } from "f2e-server3"
import { IProject } from "./interfaces"
import { addRoute, createAuthHelper } from "f2e-server3"

const db_projects = new DBFile<IProject[]>({
    filePath: path.join(process.cwd(), ".f2e_cache/projects.json"),
    initData: [],
    fileToData: (filePath) => JSON.parse(fs.readFileSync(filePath, "utf-8")),
    dataToFile: (data) => JSON.stringify(data, null, 2),
    autoSave: true,
})

const authHelper = createAuthHelper({})

/**
 * 获取项目列表
 */
addRoute("/api/projects", async (body, ctx) => {
    const projects = db_projects.data
    const user = authHelper.getLoginUser(ctx)?.user
    return projects.filter(project => project?.userId === user?.username || project.participators?.includes(user?.username || "")) || []
})

/**
 * 创建项目
 */
addRoute("/api/project/create", async (body: IProject, ctx) => {
    const proj = body
    const user = authHelper.getLoginUser(ctx)?.user
    if (!user) {
        throw new Error("Please login first")
    }
    if (!proj.name) {
        throw new Error("Name is required")
    }
    if (db_projects.data.find(project => project.id === proj.id)) {
        throw new Error("ProjectId already exists")
    }
    proj.createdAt = new Date().toLocaleString()
    proj.updatedAt = new Date().toLocaleString()
    proj.userId = user.username
    proj.userName = user.nickname || user.username
    db_projects.data.push(proj)
    return proj
})

/**
 * 更新项目
 */
addRoute("/api/project/update", async (body: IProject, ctx) => {
    const proj = body
    const user = authHelper.getLoginUser(ctx)?.user
    if (!user) {
        throw new Error("Please login first")
    }
    const index = db_projects.data.findIndex(project => project.id === proj.id)
    if (index === -1) {
        throw new Error("Project not found")
    }
    proj.updatedAt = new Date().toLocaleString()
    Object.assign(db_projects.data[index], proj)
    return db_projects.data
})

/**
 * 删除项目
 */
addRoute("/api/project/delete", async (body: { id: string | string[] }, ctx) => {
    const proj = body
    const user = authHelper.getLoginUser(ctx)?.user
    if (!user) {
        throw new Error("Please login first")
    }
    const index = db_projects.data.findIndex(project => Array.isArray(proj.id) ? proj.id.includes(project.id) : proj.id === project.id)
    if (index === -1) {
        throw new Error("Project not found")
    }
    db_projects.data.splice(index, 1)
    return db_projects.data
})